<?php

class OrderController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column1';
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Send mail method
     */
    public static function sendMail($email, $subject, $message) {
        $adminEmail = Yii::app()->params['adminEmail'];
        $headers = "MIME-Version: 1.0\r\nFrom: $adminEmail\r\nReply-To: $adminEmail\r\nContent-Type: text/html; charset=utf-8";
        $message = wordwrap($message, 70);
        $message = str_replace("\n.", "\n..", $message);
        return mail($email, '=?UTF-8?B?' . base64_encode($subject) . '?=', $message, $headers);
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {

        $users = Users::model()->findAll('superuser = :superuser', array(':superuser' => 2));
        $credit = array();
        foreach ($users as $user) {
            array_push($credit, $user->username);
        }

        $users = Users::model()->findAll('superuser = :superuser', array(':superuser' => 3));
        $warehouse = array();
        foreach ($users as $user) {
            array_push($warehouse, $user->username);
        }

        $users = Users::model()->findAll('superuser = :superuser', array(':superuser' => 4));
        $shipping = array();
        foreach ($users as $user) {
            array_push($shipping, $user->username);
        }

        $users = Users::model()->findAll('superuser = :superuser', array(':superuser' => 5));
        $account = array();
        foreach ($users as $user) {
            array_push($account, $user->username);
        }

        return array(
            array('allow', // allow all users to perform credit
                'actions' => array('credit', 'appcredit', 'igncredit'),
                'users' => $credit,
            ),
            array('allow', // allow all users to perform warehouse
                'actions' => array('warehouse', 'appwarehouse'),
                'users' => $warehouse,
            ),
            array('allow', // allow all users to perform shipping
                'actions' => array('shipping', 'ship'),
                'users' => $shipping,
            ),
            array('allow', // allow all users to perform account
                'actions' => array('account', 'collect'),
                'users' => $account,
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'thanks', 'status', 'delete'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'credit', 'warehouse', 'shipping', 'account', 'appcredit', 'igncredit', 'appwarehouse', 'ship', 'collect'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Order;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Order'])) {
            $model->attributes = $_POST['Order'];            
            if ($model->save()) {               
                $user = User::model()->find('id=:id', array(':id' => $model->customer_id));
                $this->sendMail($user->email, "Xác nhận đơn hàng #".$model->id, "Chào ".$user->username.", chúng tôi đã nhận được đơn hàng của bạn.");
                $this->redirect(array('thanks'));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Lists item to credit.
     */
    public function actionCredit() {
        $dataProvider = new CActiveDataProvider('Order', array(
                    'criteria' => array(
                        'order' => 'status_id',
                        'condition' => 'status_id = 1 OR status_id = 2 OR status_id = 3',
                    ),
                ));
        $this->render('credit', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Lists item to warehouse.
     */
    public function actionWarehouse() {
        $dataProvider = new CActiveDataProvider('Order', array(
                    'criteria' => array(
                        'order' => 'status_id',
                        'condition' => 'status_id = 3 OR status_id = 4',
                    ),
                ));
        $this->render('warehouse', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Show order status by customer.
     */
    public function actionStatus() {
        $dataProvider = new CActiveDataProvider('Order', array(
                    'criteria' => array(
                        'order' => 'customer_id',
                        'condition' => 'customer_id = :customer_id',
                        'params' => array(':customer_id' => Yii::app()->user->id),
                    ),
                ));
        $this->render('status', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Lists item to ship.
     */
    public function actionShipping() {
        $dataProvider = new CActiveDataProvider('Order', array(
                    'criteria' => array(
                        'order' => 'status_id',
                        'condition' => 'status_id = 4 OR status_id = 5',
                    ),
                ));
        $this->render('shipping', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Lists item to billing and collecting.
     */
    public function actionAccount() {
        $dataProvider = new CActiveDataProvider('Order', array(
                    'criteria' => array(
                        'order' => 'status_id',
                        'condition' => 'status_id = 5 OR status_id = 5',
                    ),
                ));
        $this->render('account', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Display thanks for customer.
     */
    public function actionThanks() {
        $this->render('thanks');
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $dataProvider = new CActiveDataProvider('Order', array(
                    'criteria' => array(
                        'order' => 'datetime desc',
                    ),
                ));
        $this->render('admin', array(
            'dataProvider' => $dataProvider,
        ));
    }

        /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     */
    public function actionDelete() {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel()->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_POST['ajax']))
                $this->redirect(array('order/status'));
        }
        else
            throw new CHttpException(400, 'Yêu cầu không đúng, vui lòng không nghịch.');
    }

    /**
     * Approves order credit.
     * If approval is successful, the browser will be redirected to the comment index page.
     */
    public function actionAppcredit() {
        if (Yii::app()->request->isPostRequest) {
            //  $order = $this->loadModel();            
            $connection = Yii::app()->db;
            $sql = "UPDATE tbl_order
            SET status_id =  '3'
            WHERE  id ='" . $_GET['id'] . "'";
            $command = $connection->createCommand($sql);
            $command->execute();
            $order = Order::model()->find('id=:id', array(':id' => $_GET['id']));
            $user = User::model()->find('id=:id', array(':id' => $order->customer_id));
            $this->sendMail($user->email, "Chấp thuận tín dụng", "Đơn hàng số #" . $_GET['id'] . " của bạn đã được chấp thuận tín dụng.");
            $this->redirect(array('credit'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Picks up in warehouse.
     * If pick up is successful, the browser will be redirected to the comment index page.
     */
    public function actionAppwarehouse() {
        if (Yii::app()->request->isPostRequest) {
            //  $order = $this->loadModel();
            $connection = Yii::app()->db;
            $sql = "UPDATE tbl_order
            SET status_id =  '4'
            WHERE  id ='" . $_GET['id'] . "'";
            $command = $connection->createCommand($sql);
            $command->execute();
            $this->redirect(array('warehouse'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Ship items.
     * If Shipping is successful, the browser will be redirected to the comment index page.
     */
    public function actionShip() {
        if (Yii::app()->request->isPostRequest) {
            //  $order = $this->loadModel();
            $connection = Yii::app()->db;
            $sql = "UPDATE tbl_order
            SET status_id =  '5'
            WHERE  id ='" . $_GET['id'] . "'";
            $command = $connection->createCommand($sql);
            $command->execute();
            $this->redirect(array('shipping'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Approves order credit.
     * If approval is successful, the browser will be redirected to the comment index page.
     */
    public function actionCollect() {
        if (Yii::app()->request->isPostRequest) {
            //  $order = $this->loadModel();
            $connection = Yii::app()->db;
            $sql = "UPDATE tbl_order
            SET status_id =  '6'
            WHERE  id ='" . $_GET['id'] . "'";
            $command = $connection->createCommand($sql);
            $command->execute();
            $this->redirect(array('account'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Ignore order credit.
     * If ignore is successful, the browser will be redirected to the comment index page.
     */
    public function actionIgncredit() {
        if (Yii::app()->request->isPostRequest) {
            $connection = Yii::app()->db;
            $sql = "UPDATE tbl_order
            SET status_id =  '2'
            WHERE  id ='" . $_GET['id'] . "'";
            $command = $connection->createCommand($sql);
            $command->execute();
            $this->redirect(array('credit'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel() {
        if ($this->_model === null) {
            if (isset($_GET['id']))
                $this->_model = Order::model()->findbyPk($_GET['id']);
            if ($this->_model === null)
                throw new CHttpException(404, 'Không tồn tại trang yêu cầu.');
        }
        return $this->_model;
//        $model = Order::model()->findByPk((int) $id);
//        if ($model === null)
//            throw new CHttpException(404, 'The requested page does not exist.');
//        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'order-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
